<template>
    <main class="main-page"  id="">
        <template v-if="pageReady">
            <template v-if="showHeader">
                <section class="page-section mb-3" >
                    <div class="container">
                        <div class="grid justify-content-between align-items-center">
                            <div  v-if="!isSubPage"  class="col-fixed " >
                                <Button @click="$router.go(-1)"   class="p-button p-button-text " icon="pi pi-arrow-left"  />
                            </div>
                            <div  class="col " >
                                <div class=" text-2xl text-primary font-bold" >
                                    {{ $t('editCours') }}
                                </div>
                            </div>
                            
                        </div>
                    </div>
                </section>
            </template>
            <section class="page-section " >
                <div class="container">
                    <div class="grid ">
                        <div  class="md:col-9 sm:col-12 comp-grid" >
                            <div >
                                <form ref="observer"  tag="form" @submit.prevent="submitForm()" :class="{ 'card ': !isSubPage }" class=" ">
                                    <!--[form-content-start]-->
                                    <div class="grid">
                                        <div class="col-12">
                                            <div class="formgrid grid">
                                                <div class="col-12 md:col-3">
                                                    {{ $t('courseId') }} *
                                                </div>
                                                <div class="col-12 md:col-9">
                                                    <InputText  ref="ctrlcourse_id" v-model.trim="formData.course_id"  :label="$t('courseId')" type="number" :placeholder="$t('enterCourseId')"   step="any"    
                                                    class=" w-full" :class="getErrorClass('course_id')">
                                                    </InputText>
                                                    <small v-if="isFieldValid('course_id')" class="p-error">{{ getFieldError('course_id') }}</small> 
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="formgrid grid">
                                                <div class="col-12 md:col-3">
                                                    {{ $t('courseName') }} *
                                                </div>
                                                <div class="col-12 md:col-9">
                                                    <InputText  ref="ctrlcourse_name" v-model.trim="formData.course_name"  :label="$t('courseName')" type="text" :placeholder="$t('enterCourseName')"      
                                                    class=" w-full" :class="getErrorClass('course_name')">
                                                    </InputText>
                                                    <small v-if="isFieldValid('course_name')" class="p-error">{{ getFieldError('course_name') }}</small> 
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="formgrid grid">
                                                <div class="col-12 md:col-3">
                                                    {{ $t('description') }} 
                                                </div>
                                                <div class="col-12 md:col-9">
                                                    <Textarea :class="getErrorClass('description')" class="w-full" ref="ctrldescription" rows="5"  v-model="formData.description" :placeholder="$t('enterDescription')"    type="textarea">
                                                    </Textarea>
                                                    <small v-if="isFieldValid('description')" class="p-error">{{ getFieldError('description') }}</small> 
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="formgrid grid">
                                                <div class="col-12 md:col-3">
                                                    {{ $t('creditHours') }} 
                                                </div>
                                                <div class="col-12 md:col-9">
                                                    <InputText  ref="ctrlcredit_hours" v-model.trim="formData.credit_hours"  :label="$t('creditHours')" type="number" :placeholder="$t('enterCreditHours')"   step="0.1"    
                                                    class=" w-full" :class="getErrorClass('credit_hours')">
                                                    </InputText>
                                                    <small v-if="isFieldValid('credit_hours')" class="p-error">{{ getFieldError('credit_hours') }}</small> 
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="formgrid grid">
                                                <div class="col-12 md:col-3">
                                                    {{ $t('dailyWeight') }} *
                                                </div>
                                                <div class="col-12 md:col-9">
                                                    <InputText  ref="ctrldaily_weight" v-model.trim="formData.daily_weight"  :label="$t('dailyWeight')" type="number" :placeholder="$t('enterDailyWeight')"   step="0.1"    
                                                    class=" w-full" :class="getErrorClass('daily_weight')">
                                                    </InputText>
                                                    <small v-if="isFieldValid('daily_weight')" class="p-error">{{ getFieldError('daily_weight') }}</small> 
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="formgrid grid">
                                                <div class="col-12 md:col-3">
                                                    {{ $t('examWeight') }} *
                                                </div>
                                                <div class="col-12 md:col-9">
                                                    <InputText  ref="ctrlexam_weight" v-model.trim="formData.exam_weight"  :label="$t('examWeight')" type="number" :placeholder="$t('enterExamWeight')"   step="0.1"    
                                                    class=" w-full" :class="getErrorClass('exam_weight')">
                                                    </InputText>
                                                    <small v-if="isFieldValid('exam_weight')" class="p-error">{{ getFieldError('exam_weight') }}</small> 
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="formgrid grid">
                                                <div class="col-12 md:col-3">
                                                    {{ $t('homeworkWeight') }} *
                                                </div>
                                                <div class="col-12 md:col-9">
                                                    <InputText  ref="ctrlhomework_weight" v-model.trim="formData.homework_weight"  :label="$t('homeworkWeight')" type="number" :placeholder="$t('enterHomeworkWeight')"   step="0.1"    
                                                    class=" w-full" :class="getErrorClass('homework_weight')">
                                                    </InputText>
                                                    <small v-if="isFieldValid('homework_weight')" class="p-error">{{ getFieldError('homework_weight') }}</small> 
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="formgrid grid">
                                                <div class="col-12 md:col-3">
                                                    {{ $t('startDate') }} 
                                                </div>
                                                <div class="col-12 md:col-9">
                                                    <Calendar  :showButtonBar="true" class="w-full" :class="getErrorClass('start_date')" dateFormat="yy-mm-dd" v-model="formData.start_date" :showIcon="true"     mask="YYYY-MM-DD"      />
                                                    <small v-if="isFieldValid('start_date')" class="p-error">{{ getFieldError('start_date') }}</small> 
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="formgrid grid">
                                                <div class="col-12 md:col-3">
                                                    {{ $t('endDate') }} 
                                                </div>
                                                <div class="col-12 md:col-9">
                                                    <Calendar  :showButtonBar="true" class="w-full" :class="getErrorClass('end_date')" dateFormat="yy-mm-dd" v-model="formData.end_date" :showIcon="true"     mask="YYYY-MM-DD"      />
                                                    <small v-if="isFieldValid('end_date')" class="p-error">{{ getFieldError('end_date') }}</small> 
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="formgrid grid">
                                                <div class="col-12 md:col-3">
                                                    {{ $t('teacherId') }} 
                                                </div>
                                                <div class="col-12 md:col-9">
                                                    <InputText  ref="ctrlteacher_id" v-model.trim="formData.teacher_id"  :label="$t('teacherId')" type="text" :placeholder="$t('enterTeacherId')"   step="any"    
                                                    class=" w-full" :class="getErrorClass('teacher_id')">
                                                    </InputText>
                                                    <small v-if="isFieldValid('teacher_id')" class="p-error">{{ getFieldError('teacher_id') }}</small> 
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="formgrid grid">
                                                <div class="col-12 md:col-3">
                                                    {{ $t('status') }} 
                                                </div>
                                                <div class="col-12 md:col-9">
                                                    <InputText  ref="ctrlstatus" v-model.trim="formData.status"  :label="$t('status')" type="text" :placeholder="$t('enterStatus')"      
                                                    class=" w-full" :class="getErrorClass('status')">
                                                    </InputText>
                                                    <small v-if="isFieldValid('status')" class="p-error">{{ getFieldError('status') }}</small> 
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="formgrid grid">
                                                <div class="col-12 md:col-3">
                                                    {{ $t('courseNumber') }} *
                                                </div>
                                                <div class="col-12 md:col-9">
                                                    <InputText  ref="ctrlcourse_number" v-model.trim="formData.course_number"  :label="$t('courseNumber')" type="text" :placeholder="$t('enterCourseNumber')"      
                                                    class=" w-full" :class="getErrorClass('course_number')">
                                                    </InputText>
                                                    <small v-if="isFieldValid('course_number')" class="p-error">{{ getFieldError('course_number') }}</small> 
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!--[form-content-end]-->
                                    <div v-if="showSubmitButton" class="text-center my-3">
                                        <Button type="submit" :label="$t('update')" icon="pi pi-send" :loading="saving" />
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </template>
        <template v-if="loading">
            <div style="min-height:200px" class="flex gap-3 justify-content-center align-items-center p-3">
                <div><ProgressSpinner style="width:50px;height:50px" /> </div>
                <div class="text-500">{{ $t('loading') }} </div>
            </div>
        </template>
    </main>
</template>
<script setup>
	import {  computed,  reactive, toRefs, onMounted } from 'vue';
	import { required, numeric, } from 'src/services/validators';
	import { useApp } from 'src/composables/app.js';
	import { useAuth } from 'src/composables/auth.js';
	import { $t } from 'src/services/i18n';
	import { useEditPage } from 'src/composables/editpage.js';
	import { usePageStore } from 'src/store/page';
	const props = defineProps({
		id: [String, Number],
		pageStoreKey: {
			type: String,
			default: 'COURSES',
		},
		pageName: {
			type: String,
			default: 'courses',
		},
		routeName: {
			type: String,
			default: 'coursesedit',
		},
		pagePath: {
			type : String,
			default : 'courses/edit',
		},
		apiPath: {
			type: String,
			default: 'courses/edit',
		},
		submitButtonLabel: {
			type: String,
			default: () => $t('update'),
		},
		formValidationError: {
			type: String,
			default: $t('formIsInvalid'),
		},
		formValidationMsg: {
			type: String,
			default: $t('pleaseCompleteTheForm'),
		},
		msgTitle: {
			type: String,
			default: $t('updateRecord'),
		},
		msgBeforeSave: {
			type: String,
			default: () => $t(''),
		},
		msgAfterSave: {
			type: String,
			default: () => $t('recordUpdatedSuccessfully'),
		},
		showHeader: {
			type: Boolean,
			default: true,
		},
		showSubmitButton: {
			type: Boolean,
			default: true,
		},
		redirect: {
			type : Boolean,
			default : true,
		},
		isSubPage: {
			type : Boolean,
			default : false,
		},
	});
	
	const auth = useAuth();
	const store = usePageStore(props.pageStoreKey);
	const app = useApp();
	
	const formDefaultValues = Object.assign({
		course_id: "", course_name: "", description: "", credit_hours: "", daily_weight: "0.30", exam_weight: "0.40", homework_weight: "0.30", start_date: new Date(), end_date: new Date(), teacher_id: "", status: "", course_number: "", 
	}, props.pageData);
	
	const formData = reactive({ ...formDefaultValues });
	
	function afterSubmit(response) {
		app.flashMsg(props.msgTitle, props.msgAfterSave);
		if(app.isDialogOpen()){
			app.closeDialogs(); // if page is open as dialog, close dialog
		}
		else if(props.redirect) {
			app.navigateTo(`/courses`);
		}
	}
	
	// form validation rules
	const rules = computed(() => {
		return {
			course_id: { required, numeric },
			course_name: { required },
			description: {  },
			credit_hours: { numeric },
			daily_weight: { required, numeric },
			exam_weight: { required, numeric },
			homework_weight: { required, numeric },
			start_date: {  },
			end_date: {  },
			teacher_id: { },
			status: {  },
			course_number: { required }
		}
	});
	
	const page = useEditPage({store, props, formData, rules, afterSubmit });
	
	const {  currentRecord: editRecord } = toRefs(store.state);
	const {  pageReady, saving, loading, } = toRefs(page.state);
	
	const { apiUrl } = page.computedProps;
	
	const { load, submitForm, getErrorClass, getFieldError, isFieldValid,  } = page.methods;
	
	onMounted(()=>{
		const pageTitle = $t('editCours');
		app.setPageTitle(props.routeName, pageTitle); // set browser page title
	});
</script>
<style scoped>
</style>
